package com.lqq.chapter03.lock;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author lqq677
 * @Date 2021/8/10 10:24
 * @Description 定制化线程间通信
 */
//第一步 创建资源类
class ShareResource {
    //标志位
    private Integer flag = 1; // 1 AA     2 BB     3 CC
    //创建lock锁
    Lock lock = new ReentrantLock();
    //创建3个condition
    Condition c1 = lock.newCondition();
    Condition c2 = lock.newCondition();
    Condition c3 = lock.newCondition();

    //打印5次，参数第几轮
    public void print5(int loop) {
         lock.lock();
          try {
              //判断
              if (flag != 1) {
                  c1.await();
              }
              //干活
              for (int i = 1; i <=5; i++) {
                  System.out.println(Thread.currentThread().getName()+" :: "+i+" ：轮数："+loop);
              }
              //通知BB
              this.flag = 2;
              c2.signal();

         }catch (Exception e){
             e.printStackTrace();
         }finally {
             lock.unlock();
         }
    }

    //打印10次，参数第几轮
    public void print10(int loop) {
        lock.lock();
        try {
            //判断
            if (flag != 2) {
                c2.await();
            }
            //干活
            for (int i = 1; i <=10; i++) {
                System.out.println(Thread.currentThread().getName()+" :: "+i+" ：轮数："+loop);
            }
            //通知BB
            this.flag = 3;
            c3.signal();

        }catch (Exception e){
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }

    //打印5次，参数第几轮
    public void print15(int loop) {
        lock.lock();
        try {
            //判断
            if (flag != 3) {
                c3.await();
            }
            //干活
            for (int i = 1; i <=15; i++) {
                System.out.println(Thread.currentThread().getName()+" :: "+i+" ：轮数："+loop);
            }
            //通知BB
            this.flag = 1;
            c1.signal();

        }catch (Exception e){
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }

}


public class ThreadSignal {
    public static void main(String[] args) {

        //资源对象
        ShareResource share = new ShareResource();

        //AA，5次打印
        new Thread(() ->{
            for (int i = 1; i <= 10; i++) {
                share.print5(i);
            }
                }, "AA").start();

        //BB，10次打印
        new Thread(() ->{
            for (int i = 1; i <= 10; i++) {
                share.print10(i);
            }
        }, "BB").start();

        //CC，15次打印
        new Thread(() ->{
            for (int i = 1; i <= 10; i++) {
                share.print15(i);
            }
        }, "CC").start();

    }

}
